<template>
  <div class="traceability-detail">
    <!-- 顶部操作区 -->
    <el-row class="header">
      <el-col :span="24" style="display: flex; justify-content: flex-end; align-items: center;">
        <el-button type="danger" icon="el-icon-delete" style="margin-left: 8px;">删除</el-button>
        <el-button type="primary" icon="el-icon-edit" style="margin-left: 8px;">修改基本信息</el-button>
        <el-button icon="el-icon-download" style="margin-left: 8px;">导出溯源码</el-button>
      </el-col>
    </el-row>

    <el-divider />

    <!-- 产品信息区 -->
    <el-card class="mb16">
      <el-row :gutter="24" align="top">
        <!-- 左侧产品图片 -->
        <el-col :span="4" style="display: flex; justify-content: center;">
          <el-image :src="product.cover" fit="cover" class="product-img" />
        </el-col>
        <!-- 右侧产品信息 -->
        <el-col :span="20">
          <div class="product-title">{{ product.productName }}</div>
          <el-row class="product-info-row">
            <el-col :span="12">
              <div>生产批次：{{ product.batch }}</div>
            </el-col>
            <el-col :span="12">
              <div>保质期：{{ product.shelf_life }}</div>
            </el-col>
          </el-row>
          <el-row class="product-info-row">
            <el-col :span="12">
              <div>生产许可证号：{{ product.license }}</div>
            </el-col>
            <el-col :span="12">
              <div>生产企业：{{ product.enterprise }}</div>
            </el-col>
          </el-row>
          <!-- 产品检验报告 -->
          <div class="section-title" style="margin-top: 20px;">产品检验报告</div>
          <Image
            :type="1"
            label="产品检验报告"
            :production-batch="String(route.query.Batch || '')"
            class="standard-uploader"
          />
        </el-col>
      </el-row>
    </el-card>

    <!-- 三个tab区域 -->
    <el-tabs v-model="activeTab">
      <el-tab-pane label="养殖信息" name="farming">
        <!-- 养殖信息列表 -->
        <el-card class="mb16">
          <div style="display: flex; align-items: center; margin-bottom: 12px;">
            <span class="section-title">养殖信息</span>
            <el-button type="primary" size="small" icon="el-icon-setting" style="margin-left: 12px;" @click="openFarmingDialog">设置</el-button>
          </div>
          <el-row :gutter="24">
            <!-- 左列 -->
            <el-col :span="12">
              <div style="margin-bottom: 12px;">品种：{{ farmingInfo.breed }}</div>
              <div style="margin-bottom: 12px;">饲养天数：{{ farmingInfo.days }}</div>
              <div style="margin-bottom: 12px;">饲养负责人：{{ farmingInfo.caretaker }}</div>
            </el-col>
            <!-- 右列 -->
            <el-col :span="12">
              <div style="margin-bottom: 12px;">来源：{{ farmingInfo.source }}</div>
              <div style="margin-bottom: 12px;">饲料品牌：{{ farmingInfo.brand }}</div>
              <div style="margin-bottom: 12px;">出栏日期：{{ farmingInfo.departure }}</div>
            </el-col>
          </el-row>
        </el-card>

        <!-- 保健信息列表 -->
        <el-card class="mb16" v-if="activeTab === 'farming'">
          <div style="display: flex; align-items: center; margin-bottom: 12px;">
            <span class="section-title">保健信息</span>
            <el-button type="primary" size="small" style="margin-left: 12px;" @click="addHealthcareRow">新增行</el-button>
          </div>
          <el-table :data="healthcareList" border style="width: 100%;">
            <el-table-column prop="days" label="饲养天数" width="120">
              <template #default="scope">
                <template v-if="scope.row.editing">
                  <el-input-number v-model="scope.row.days" size="small" :min="0" />
                </template>
                <template v-else>
                  {{ scope.row.days }}
                </template>
              </template>
            </el-table-column>
            <el-table-column prop="way" label="保健方式" width="180">
              <template #default="scope">
                <template v-if="scope.row.editing">
                  <el-input v-model="scope.row.way" size="small" />
                </template>
                <template v-else>
                  {{ scope.row.way }}
                </template>
              </template>
            </el-table-column>
            <el-table-column prop="method" label="保健方法" width="180">
              <template #default="scope">
                <template v-if="scope.row.editing">
                  <el-input v-model="scope.row.method" size="small" />
                </template>
                <template v-else>
                  {{ scope.row.method }}
                </template>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="160">
              <template #default="scope">
                <template v-if="scope.row.editing">
                  <el-button type="primary" size="small" @click="saveHealthcareRow">保存</el-button>
                  <el-button size="small" @click="cancelHealthcareRow(scope.$index)">取消</el-button>
                </template>
                <template v-else>
                  <el-button type="text" size="small" @click="startEditing(scope.row)">修改</el-button>
                  <el-button type="text" size="small" style="color: #F56C6C;" @click="deleteHealthcareRow(scope.row.id)">删除</el-button>
                </template>
              </template>
            </el-table-column>
          </el-table>
        </el-card>

        <!-- 动检证 -->
        <el-card class="mb16" v-if="activeTab === 'farming'">
          <div class="section-title">动检证</div>
          <Image
          :type="2"
          label="动物检疫证明"
          :production-batch="String(route.query.Batch || '')"
          class="standard-uploader"
        />
        </el-card>

        <!-- 养殖企业信息 -->
        <el-card class="mb16">
          <div style="display: flex; align-items: center; margin-bottom: 12px;">
            <span class="section-title" style="font-size:20px;font-weight:bold;">企业信息</span>
            <el-button type="primary" size="small" icon="el-icon-setting" style="margin-left: 12px;" @click="openCompanyDialog">设置1</el-button>
          </div>
          <el-divider style="margin: 8px 0 24px 0;" />
          <el-row>
            <el-col :span=12>
              <div style="margin-bottom: 12px;">养殖场：{{ companyForm.farm || '暂无数据' }}</div>
              <div style="margin-bottom: 12px;">存栏数量：{{ companyForm.number ? companyForm.number + ' 只' : '暂无数据' }}</div>
            </el-col>
            <el-col :span=12>
              <div style="margin-bottom: 12px;">负责人：{{ companyForm.principal || '暂无数据' }}</div>
            </el-col>
          </el-row>
        </el-card>

        <!-- 养殖企业照片 -->
        <el-card>
          <div class="section-title">企业照片</div>
          <Image
            :type="3"
            label="养殖企业照片"
            :production-batch="String(route.query.Batch || '')"
            class="standard-uploader"
          />
        </el-card>
<!-- 养殖信息弹出框 -->
        <el-dialog v-model="farmingDialogVisible" title="养殖信息" width="600px" :close-on-click-modal="false">
          <el-form ref="farmingFormRef" :model="farmingForm" :rules="farmingRules" label-width="110px" style="padding: 0 20px;">
            <el-form-item label="品种：" prop="breed" required>
              <el-input v-model="farmingForm.breed" maxlength="30" show-word-limit placeholder="请输入品种" />
            </el-form-item>
            <el-form-item label="来源：" prop="source" required>
              <el-input v-model="farmingForm.source" maxlength="30" show-word-limit placeholder="请输入来源" />
            </el-form-item>
            <el-form-item label="饲养天数：" prop="days" required>
              <el-input v-model="farmingForm.days" maxlength="5" show-word-limit placeholder="请输入饲养天数" />
            </el-form-item>
            <el-form-item label="饲料品牌：" prop="brand">
              <el-input v-model="farmingForm.brand" maxlength="30" show-word-limit placeholder="请输入饲料品牌" />
            </el-form-item>
            <el-form-item label="饲养负责人：" prop="caretaker" required>
              <el-input v-model="farmingForm.caretaker" maxlength="30" show-word-limit placeholder="请输入负责人" />
            </el-form-item>
            <el-form-item label="出栏日期：" prop="departure" required>
              <el-date-picker v-model="farmingForm.departure" type="date" value-format="YYYY-MM-DD" placeholder="请选择出栏日期" style="width: 100%;" />
            </el-form-item>
          </el-form>
          <template #footer>
            <div style="padding: 0 20px 20px;">
              <el-button type="primary" @click="handleFarmingSave">保存</el-button>
            </div>
          </template>
        </el-dialog>
<!-- 养殖企业信息弹出框 -->
        <el-dialog v-model="companyDialogVisible" title="企业信息" width="800px" :close-on-click-modal="false">
          <el-form ref="companyFormRef" :model="companyForm" :rules="companyRules" label-width="110px" style="padding: 0 20px;">
            <el-form-item label="养殖场：" prop="farm" required>
              <el-input v-model="companyForm.farm" maxlength="30" show-word-limit placeholder="请输入养殖场" />
            </el-form-item>
            <el-form-item label="负责人：" prop="principal" required>
              <el-input v-model="companyForm.principal" maxlength="30" show-word-limit placeholder="请输入负责人" />
            </el-form-item>
            <el-form-item label="存栏数量（只）：" prop="number" required>
              <el-input v-model="companyForm.number" maxlength="5" show-word-limit placeholder="请输入存栏数量" />
            </el-form-item>
          </el-form>
          <template #footer>
            <div style="padding: 0 20px 20px;">
              <el-button type="primary" @click="handleCompanySave">保存</el-button>
            </div>
          </template>
        </el-dialog>
      </el-tab-pane>


<!-- 屠宰信息 -->

      <el-tab-pane label="屠宰信息" name="slaughter">
        <!-- 屠宰信息列表 -->
        <el-card class="mb16">
          <div style="display: flex; align-items: center; margin-bottom: 12px;">
            <span class="section-title" style="font-size:20px;font-weight:bold;">屠宰信息</span>
            <el-button type="primary" size="small" icon="el-icon-setting" style="margin-left: 12px;" @click="openSlaughterDialog">设置</el-button>
          </div>
          <el-row :gutter="24">
            <el-col :span="12">
              <div style="margin-bottom: 12px;">批次：{{ slaughterInfo.batch || '-' }}</div>
              <div style="margin-bottom: 12px;">到厂时间：{{ slaughterInfo.arrivalTime ? formatDateTime(slaughterInfo.arrivalTime) : '-' }}</div>
            </el-col>
            <el-col :span="12">
              <div style="margin-bottom: 12px;">到厂均重：{{ slaughterInfo.counterBalance ? slaughterInfo.counterBalance + ' 公斤' : '-' }}</div>
              <div style="margin-bottom: 12px;">屠宰时间：{{ slaughterInfo.slaughter_Time ? formatDateTime(slaughterInfo.slaughter_Time) : '-' }}</div>
            </el-col>
          </el-row>
        </el-card>
        <!-- 相关资质 -->
        <el-card class="mb16">
          <div class="section-title">相关资质</div>
          <Image
            :type="4"
            label="宰前检疫"
            :production-batch="String(route.query.Batch || '')"
            class="standard-uploader"
          />
        </el-card>
        <!-- 屠宰企业信息显示列表 -->
        <el-card class="mb16">
          <div style="display: flex; align-items: center; margin-bottom: 12px;">
            <span class="section-title" style="color:#409EFF;font-size:20px;font-weight:bold;">企业信息</span>
            <el-button type="primary" size="small" icon="el-icon-setting" style="margin-left: 12px;" @click="openSlaughterCompanyDialog">设置1</el-button>
          </div>
          <el-divider style="margin: 8px 0 24px 0;" />
          <el-row>
            <el-col :span="12">
              <div style="margin-bottom: 12px;">公司名称：{{ slaughterCompanyInfo?.companyName || '-' }}</div>
              <div style="margin-bottom: 12px;">公司地址：{{ slaughterCompanyInfo?.companyAddress || '-' }}</div>
            </el-col>
            <el-col :span="12">
              <div style="margin-bottom: 12px;">成立时间：{{ slaughterCompanyInfo?.establishedTime || '-' }}</div>
            </el-col>
          </el-row>
          <div style="margin-top: 12px;">公司简介：</div>
          <div style="white-space: pre-line; word-break: break-all; margin-left: 16px;">
            {{ slaughterCompanyInfo?.resume || '-' }}
          </div>
        </el-card>
        <!-- 屠宰企业照片 -->
        <el-card>
          <div class="section-title">企业照片</div>
          <Image
            :type="5"
            label="屠宰企业照片"
            :production-batch="String(route.query.Batch || '')"
            class="standard-uploader"
          />
        </el-card>
        <!-- 屠宰信息弹出框 -->
        <el-dialog v-model="slaughterDialogVisible" title="屠宰信息" width="600px" :close-on-click-modal="false">
          <el-form ref="slaughterFormRef" :model="slaughterForm" :rules="slaughterRules" label-width="140px" style="padding: 0 20px;">
            <el-form-item label="批次：" prop="batch" required>
              <el-input v-model="slaughterForm.batch" maxlength="20" show-word-limit placeholder="请输入批次（20位数字）" disabled />
            </el-form-item>
            <el-form-item label="到厂均重（公斤）：" prop="counterBalance" required>
              <el-input v-model="slaughterForm.counterBalance" maxlength="5" show-word-limit placeholder="请输入到厂均重" />
            </el-form-item>
            <el-form-item label="到厂时间：" prop="arrivalTime" required>
              <el-date-picker 
                v-model="slaughterForm.arrivalTime" 
                type="datetime" 
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择到厂时间" 
                style="width: 100%;" 
              />
            </el-form-item>
            <el-form-item label="屠宰时间：" prop="slaughter_Time" required>
              <el-date-picker 
                v-model="slaughterForm.slaughter_Time" 
                type="datetime" 
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择屠宰时间" 
                style="width: 100%;" 
              />
            </el-form-item>
          </el-form>
          <template #footer>
            <div style="padding: 0 20px 20px;">
              <el-button type="primary" @click="handleSlaughterSave">保存</el-button>
            </div>
          </template>
        </el-dialog>
        <!-- 屠宰公司信息弹出框 -->
        <el-dialog v-model="slaughterCompanyDialogVisible" title="企业信息" width="600px" :close-on-click-modal="false">
          <el-form ref="slaughterCompanyFormRef" :model="slaughterCompanyForm" :rules="slaughterCompanyRules" label-width="110px" style="padding: 0 20px;">
            <el-form-item label="公司名称：" prop="companyName" required>
              <el-input v-model="slaughterCompanyForm.companyName" maxlength="30" show-word-limit placeholder="请输入公司名称" />
            </el-form-item>
            <el-form-item label="公司地址：" prop="companyAddress" required>
              <div style="display: flex; gap: 8px;">
                <el-cascader
                  v-model="slaughterCompanyForm.companyAddress"
                  :options="addressOptions"
                  placeholder="请选择省/市/区"
                  @change="handleAddressChange"
                  style="width: 50%;"
                />
                <el-input
                  v-model="slaughterCompanyForm.regionName"
                  maxlength="100"
                  show-word-limit
                  placeholder="请输入详细地址"
                  style="width: 50%;"
                />
              </div>
            </el-form-item>
            <el-form-item label="成立时间：" prop="establishedTime" required>
              <el-date-picker
                v-model="slaughterCompanyForm.establishedTime"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择成立时间"
                style="width: 100%;"
              />
            </el-form-item>
            <el-form-item label="公司简介：" prop="resume">
              <el-input
                type="textarea"
                v-model="slaughterCompanyForm.resume"
                maxlength="500"
                show-word-limit
                :autosize="{ minRows: 4, maxRows: 8 }"
                placeholder="请输入公司简介"
              />
            </el-form-item>
          </el-form>
          <template #footer>
            <div style="padding: 0 20px 20px;">
              <el-button type="primary" @click="handleSlaughterCompanySave">保存</el-button>
            </div>
          </template>
        </el-dialog>
      </el-tab-pane>

      <!-- 深加工信息列表 -->
      <el-tab-pane label="深加工信息" name="deep">
        <el-card class="mb16" v-if="activeTab === 'deep'">
          <div style="display: flex; align-items: center; margin-bottom: 12px;">
            <span class="section-title" style="font-size:20px;font-weight:bold;">深加工信息</span>
            <el-button type="primary" size="small" icon="el-icon-setting" style="margin-left: 12px;" @click="openDeepInfoDialog">设置</el-button>
          </div>
          <el-divider style="margin: 8px 0 24px 0;" />
          <el-row :gutter="24">
            <el-col :span="12">
              <div style="margin-bottom: 12px;">项目组：{{ deepInfoForm.team || '-' }}</div>
            </el-col>
            <el-col :span="12">
              <div style="margin-bottom: 12px;">负责人：{{ deepInfoForm.principal || '-' }}</div>
            </el-col>
          </el-row>
        </el-card>

        <!-- 食品安全信息 -->
        <el-card class="mb16">
          <div class="section-title">食品安全信息</div>
          <Image
            :type="6"
            label="食品安全检测报告"
            :production-batch="String(route.query.Batch || '')"
            class="standard-uploader"
          />
        </el-card>

        <!-- 供应商信息列表 -->
        <el-card class="mb16">
          <div class="section-title">供应商信息</div>
          <el-row :gutter="16">
            <el-col :span="24" v-for="(supplier, sidx) in suppliers" :key="sidx">
              <el-card class="mb16">
                <div style="display: flex; align-items: center; margin-bottom: 12px;">
                  <span class="section-title">{{ supplier.type }}</span>
                  <el-button type="primary" size="small" icon="el-icon-setting" style="margin-left: 12px;" @click="openSupplierDialog(supplier)">设置</el-button>
                </div>
                <div style="margin-bottom: 12px;">供应商生产批次：{{ supplier.supplierBatch || '-' }}</div>
                <div>相关材料</div>
                <el-row :gutter="16">
                  
                  <el-col :span="6">
                    <Image
                      :type="7 + sidx"
                      :label="supplier.type + '供应商资质材料'"
                      :production-batch="String(route.query.Batch || '')"
                      class="standard-uploader"
                    />
                  </el-col>
                </el-row>
              </el-card>
            </el-col>
          </el-row>
        </el-card>

        <!-- 深加工企业信息列表 -->
        <el-card class="mb16">
          <div style="display: flex; align-items: center; margin-bottom: 12px;">
            <span class="section-title" style="font-size:20px;font-weight:bold;">企业信息</span>
            <el-button type="primary" size="small" icon="el-icon-setting" style="margin-left: 12px;" @click="openDeepCompanyDialog">设置</el-button>
          </div>
          <el-divider style="margin: 8px 0 24px 0;" />
          <el-row :gutter="24">
            <el-col :span="12">
              <div style="margin-bottom: 12px;">公司名称：{{ deepInfoForm.companyName || '-' }}</div>
            </el-col>
            <el-col :span="12">
              <div style="margin-bottom: 12px;">生产许可证号：{{ deepInfoForm.license_Number || '-' }}</div>
            </el-col>
          </el-row>
        </el-card>

        <!-- 深加工企业照片 -->
        <el-card>
          <div class="section-title">企业照片</div>
          <Image
            :type="11"
            label="深加工企业照片"
            :production-batch="String(route.query.Batch || '')"
            class="standard-uploader"
          />
        </el-card>


<!-- 深加工信息弹出框 -->
        <el-dialog v-model="deepInfoDialogVisible" title="深加工信息" width="500px" :close-on-click-modal="false">
          <el-form ref="deepInfoFormRef" :model="deepInfoForm" :rules="deepInfoRules" label-width="110px" style="padding: 0 20px;">
            <el-form-item label="项目组：" prop="team" required>
              <el-input v-model="deepInfoForm.team" maxlength="30" show-word-limit placeholder="请输入项目组" />
            </el-form-item>
            <el-form-item label="负责人：" prop="principal" required>
              <el-input v-model="deepInfoForm.principal" maxlength="30" show-word-limit placeholder="请输入负责人" />
            </el-form-item>
          </el-form>
          <template #footer>
            <div style="padding: 0 20px 20px;">
              <el-button type="primary" @click="handleDeepInfoSave">保存</el-button>
            </div>
          </template>
        </el-dialog>

<!-- 深加工企业信息弹框 -->
        <el-dialog v-model="deepCompanyDialogVisible" title="企业信息" width="500px" :close-on-click-modal="false">
          <el-form ref="deepCompanyFormRef" :model="deepInfoForm" :rules="deepCompanyRules" label-width="110px" style="padding: 0 20px;">
            <el-form-item label="公司名称：" prop="companyName" required>
              <el-input v-model="deepInfoForm.companyName" maxlength="30" show-word-limit placeholder="请输入公司名称" />
            </el-form-item>
            <el-form-item label="生产许可证号：" prop="license_Number" required>
              <el-input v-model="deepInfoForm.license_Number" maxlength="30" show-word-limit placeholder="请输入生产许可证号" />
            </el-form-item>
          </el-form>
          <template #footer>
            <div style="padding: 0 20px 20px;">
              <el-button type="primary" @click="handleDeepInfoSave">保存</el-button>
            </div>
          </template>
        </el-dialog>
            </el-tab-pane>

        <!-- 供应商信息弹出框 -->
        <el-dialog v-model="supplierDialogVisible" :title="currentSupplier?.type" width="500px" :close-on-click-modal="false">
          <el-form ref="supplierFormRef" :model="supplierForm" :rules="supplierRules" label-width="140px" style="padding: 0 20px;">
            <el-form-item label="供应商生产批次：" prop="supplierBatch" required>
              <el-input v-model="supplierForm.supplierBatch" maxlength="20" show-word-limit placeholder="请输入供应商生产批次" />
            </el-form-item>
          </el-form>
          <template #footer>
            <div style="padding: 0 20px 20px;">
              <el-button type="primary" @click="handleSupplierSave">保存</el-button>
            </div>
          </template>
        </el-dialog>
      </el-tabs>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, watch } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import type { UploadFile, UploadFiles, UploadUserFile, UploadRawFile, UploadProps } from 'element-plus'
import { ElMessage } from 'element-plus'
import { ElImageViewer } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { useRoute } from 'vue-router'
import { onMounted } from 'vue'
import axios from 'axios'
import { provinceAndCityData } from 'element-china-area-data'
import Image from '@/components/Image.vue'  // 添加导入

const route = useRoute()
const activeTab = ref('farming')  // 移动到这里

// 深加工信息相关
interface DeepProcessingInfo {
  id: number;
  team: string;
  companyName: string;
  license_Number: string;
  principal: string;
  batch: string;
}

const deepInfoForm = ref<DeepProcessingInfo>({
  id: 0,
  team: '',
  principal: '',
  companyName: '',
  license_Number: '',
  batch: ''
})

// 深加工信息弹窗相关
const deepInfoDialogVisible = ref(false)
const deepInfoFormRef = ref<FormInstance>()

// 深加工信息表单验证规则
const deepInfoRules = reactive<FormRules>({
  team: [
    { required: true, message: '请输入项目组', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5a-zA-Z]{1,30}$/, message: '仅限中文或字母，最多30位', trigger: 'blur' }
  ],
  principal: [
    { required: true, message: '请输入负责人', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5a-zA-Z]{1,30}$/, message: '仅限中文或字母，最多30位', trigger: 'blur' }
  ]
})

// 加载深加工信息
const loadDeepInfo = async () => {
  const batch = route.query.Batch;
  if (!batch) {
    console.warn('生产批次不存在');
    return;
  }

  try {
    const res = await axios.get("http://localhost:5045/api/Slaughterhouse/GetSlaughterhouseTableShow", {
      params: { batch, type: 1 }  // 添加type参数，获取深加工信息
    });
    
    if (res.data.code === 200 && res.data.data) {
      const data = Array.isArray(res.data.data) ? res.data.data[0] : res.data.data;
      if (data) {
        deepInfoForm.value = {
          id: data.id || 0,
          team: data.team || '',
          principal: data.principal || '',
          companyName: data.companyName || '',
          license_Number: data.license_Number || '',
          batch: batch as string
        };
      }
    }
  } catch (error) {
    console.error('获取深加工信息失败:', error);
  }
};

// 打开深加工信息弹窗
const openDeepInfoDialog = async () => {
  const batch = route.query.Batch;
  if (!batch) {
    ElMessage.error('生产批次不能为空');
    return;
  }

  deepInfoDialogVisible.value = true;
};

// 保存深加工信息
const handleDeepInfoSave = async () => {
  if (!deepInfoFormRef.value) return;

  await deepInfoFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        const data = {
          ...deepInfoForm.value,
          batch: typeof route.query.Batch === 'string' ? route.query.Batch : '',
          type: 1  // 添加type字段，1表示深加工信息
        };

        const res = await axios.post("http://localhost:5045/api/Slaughterhouse/AddSlaughterhouseTable", data);
        
        if (res.data.code === 200) {
          ElMessage.success(res.data.message || '保存成功');
          deepInfoDialogVisible.value = false;
          // 重新加载深加工信息
          await loadDeepInfo();
        } else {
          ElMessage.error(res.data.message || '保存失败');
        }
      } catch (error) {
        console.error('保存深加工信息失败:', error);
        ElMessage.error('保存失败');
      }
    }
  });
};

// 监听标签页变化
watch(activeTab, async (newTab) => {
  if (newTab === 'deep') {
    const batch = route.query.Batch;
    if (batch) {
      try {
        // 同时加载两个信息
        await Promise.all([
          loadDeepInfo(),

        ]);
      } catch (error) {
        console.error('加载深加工相关信息失败:', error);
      }
    }
  }
});

// 监听批次变化
watch(
  () => route.query.Batch,
  async (newBatch) => {
    if (newBatch && activeTab.value === 'deep') {
      try {
        // 同时加载两个信息
        await Promise.all([
          loadDeepInfo(),
       
        ]);
      } catch (error) {
        console.error('批次变化，加载深加工相关信息失败:', error);
      }
    }
  }
);

// 组件挂载时初始化数据
onMounted(async () => {
  const batch = route.query.Batch;
  if (batch) {
    try {
      // 同时加载两个信息
      await Promise.all([
        loadDeepInfo(),
     
      ]);
    } catch (error) {
      console.error('初始化深加工相关信息失败:', error);
    }
  }
});

// 把商品信息反填到详情页面显示
const LoadInfo = async () => {
  const batch = route.query.Batch

  try {
    const res = await axios.get("http://localhost:5045/api/Traceability/GetTraceShow", { params: { Batch:batch } })
    const info = res.data.data
    console.log('接口返回：', info)
    product.value = {
      ...product.value,
      ...info
    }
  } catch (e) {
    ElMessage.error('获取产品信息失败')
  }
}
//商品信息数据
const product = ref({
  cover: '',
  productName: '',
  batch: '',
  shelf_life: '',
  license: '',
  enterprise: '',
  reports: []
})

//养殖信息数据显示
const farmingInfo = ref({
  id: 0,
  breed: '',
  days: '',
  caretaker: '',
  source: '',
  brand: '',
  departure: '',
  batch: typeof route.query.Batch === 'string' ? route.query.Batch : ''
})

interface CultivationItem {
  id: number;
  breed: string;
  days: string;
  caretaker: string;
  source: string;
  brand: string;
  departure: string;
  batch: string;
}

// 养殖信息列表
const cultivationList = ref<CultivationItem[]>([])

// 加载养殖信息列表
const loadCultivationList = async () => {
  const batch = typeof route.query.Batch === 'string' ? route.query.Batch : '';
  try {
    const res = await axios.get("http://localhost:5045/api/Traceability/GetCultivationShow", {
      params: { batch }
    })
    
    if (res.data.code === 200 && res.data.data) {
      const data = Array.isArray(res.data.data) ? res.data.data[0] : res.data.data;
      if (data) {
        farmingInfo.value = {
          id: data.id || 0,
          breed: data.breed || '',
          days: data.days || '',
          caretaker: data.caretaker || '',
          source: data.source || '',
          brand: data.brand || '',
          departure: data.departure ? data.departure.split('T')[0] : '',
          batch: data.batch || batch
        };
      } else {
        // 如果没有数据，使用空值但不提示错误
        farmingInfo.value = {
          id: 0,
          breed: '',
          days: '',
          caretaker: '',
          source: '',
          brand: '',
          departure: '',
          batch: batch
        };
      }
    }
  } catch (error) {
    console.error('获取养殖信息失败:', error);
    // 出错时使用空值但不提示错误
    farmingInfo.value = {
      id: 0,
      breed: '',
      days: '',
      caretaker: '',
      source: '',
      brand: '',
      departure: '',
      batch: batch
    };
  }
}

const qualifications = ref([])
const company = ref({
  name: '', foundDate: '', address: '', intro: '', photos: []
})

// 养殖信息弹窗相关
const farmingDialogVisible = ref(false)
const farmingFormRef = ref<FormInstance>()
// 养殖信息表单
const farmingForm = ref({
  id: 0,
  breed: '',
  source: '',
  days: '',
  brand: '',
  caretaker: '',
  departure: '',
  batch: typeof route.query.Batch === 'string' ? route.query.Batch : ''
})
//养殖信息表单验证规则
const farmingRules: FormRules = {
  breed: [
    { required: true, message: '请输入品种', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5a-zA-Z]{1,30}$/, message: '仅限中文或字母，最多30位', trigger: 'blur' }
  ],
  source: [
    { required: true, message: '请输入来源', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5a-zA-Z]{1,30}$/, message: '仅限中文或字母，最多30位', trigger: 'blur' }
  ],
  days: [
    { required: true, message: '请输入饲养天数', trigger: 'blur' },
    { pattern: /^\d{1,5}$/, message: '仅限数字，最多5位', trigger: 'blur' }
  ],
  brand: [
    { required: false },
    { max: 30, message: '最多30位字符', trigger: 'blur' }
  ],
  caretaker: [
    { required: true, message: '请输入负责人', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5a-zA-Z]{1,30}$/, message: '仅限中文或字母，最多30位', trigger: 'blur' }
  ],
  departure: [
    { required: true, message: '请选择出栏日期', trigger: 'change' }
  ]
}

// 更新companyForm的类型定义
const companyForm = reactive({
  id: 0,
  farm: '',
  principal: '',
  number: '',
  batch: ''
})

// 养殖企业信息显示
const loadCompanyInfo = () => {
  const batch = typeof route.query.Batch === 'string' ? route.query.Batch : '';
  try {
    axios.get("http://localhost:5045/api/Company/GetCultivationTableShow", {
      params: { batch: batch }
    })
    .then(res => {
      if (res.data.code === 200 && res.data.data) {
        const data = Array.isArray(res.data.data) ? res.data.data[0] : res.data.data;
        // 使用解构赋值更新数据
        Object.assign(companyForm, {
          id: data.id || 0,
          farm: data.farm || '',
          principal: data.principal || '',
          number: data.number || '',
          batch: batch
        });
      }
    })
  } catch (error) {
    console.error('获取企业信息失败:', error)
    ElMessage.error('获取企业信息失败')
  }
}

// 企业信息弹窗相关
const companyDialogVisible = ref(false)
const companyFormRef = ref<FormInstance>()
// 企业信息表单验证
const companyRules: FormRules = {
  farm: [
    { required: true, message: '请输入养殖场', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5a-zA-Z]{1,30}$/, message: '仅限中文或字母，最多30位', trigger: 'blur' }
  ],
  principal: [
    { required: true, message: '请输入负责人', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5a-zA-Z]{1,30}$/, message: '仅限中文或字母，最多30位', trigger: 'blur' }
  ],
  number: [
    { required: true, message: '请输入存栏数量', trigger: 'blur' },
    { pattern: /^\d{1,5}$/, message: '仅限数字，最多5位', trigger: 'blur' }
  ]
}

// 屠宰信息相关数据
const slaughterCerts = ref([
  { name: '宰前检疫', url: 'https://example.com/pre.jpg' },
  { name: '宰后质检', url: 'https://example.com/post.jpg' }
])

// 深加工信息相关数据
const foodSafetyImages = ref([
  { name: '人员卫生规范', url: 'https://example.com/food1.jpg' },
  { name: '抽检报告', url: 'https://example.com/food2.jpg' }
])

// 当前选中的供应商
// 供应商相关的接口定义
interface SupplierData {
  id: number;
  batch: string;
  type: number;
  supplierBatch: string;
  isDeleted: boolean;
}

interface SupplierMaterial {
  name: string;
  url: string;
}

interface Supplier {
  id: number;
  type: string;
  typeCode: number;
  supplierBatch: string;
  materials: SupplierMaterial[];
}

// 供应商类型映射
const supplierTypeMap: Record<number, string> = {
  1: '原料',
  2: '辅料',
  3: '添加剂',
  4: '包材'
}

// 供应商列表数据初始化
const initializeSuppliers = () => {
  return Object.entries(supplierTypeMap).map(([code, type]) => ({
    id: 0,
    type,
    typeCode: Number(code),
    supplierBatch: '',
    materials: [
      { name: '检验报告', url: '' },
      { name: '进厂验收记录', url: '' },
      { name: '供应商资质', url: '' }
    ]
  }))
}

const suppliers = ref<Supplier[]>(initializeSuppliers())

// 加载供应商信息
const loadSupplierInfo = async () => {
  const batch = route.query.Batch as string
  if (!batch) {
    console.warn('生产批次不存在')
    return
  }

  try {
    console.log('开始加载供应商信息，batch:', batch)
    const res = await axios.get("http://localhost:5045/api/Supplier/GetSupplierShow", {
      params: { batch }
    })

    if (res.data.code === 200) {
      let supplierData = res.data.data
      
      // 确保 supplierData 是数组
      if (!Array.isArray(supplierData)) {
        supplierData = supplierData ? [supplierData] : []
      }

      console.log('获取到的供应商数据:', supplierData)

      // 重置供应商列表
      suppliers.value = initializeSuppliers()

      // 遍历每个类型的供应商
      suppliers.value = suppliers.value.map(supplier => {
        // 查找对应类型的供应商数据
        const matchedData = supplierData.find((data: SupplierData) => {
          // 检查类型匹配和批次匹配
          const isMatch = data && 
                         Number(data.type) === supplier.typeCode && 
                         !data.isDeleted && 
                         data.batch === batch
          
          console.log(`检查供应商匹配 - 类型: ${supplier.type}, 编码: ${supplier.typeCode}`, {
            dataType: data?.type,
            supplierBatch: data?.supplierBatch,
            isMatch,
            data
          })
          
          return isMatch
        })

        if (matchedData) {
          console.log(`找到供应商数据 - 类型: ${supplier.type}, 批次: ${matchedData.supplierBatch}`)
          return {
            ...supplier,
            id: matchedData.id,
            supplierBatch: matchedData.supplierBatch || '',
            type: supplierTypeMap[supplier.typeCode],
            typeCode: supplier.typeCode
          }
        }
        
        console.log(`未找到供应商数据 - 类型: ${supplier.type}, 使用默认值`)
        return {
          ...supplier,
          supplierBatch: '',
          type: supplierTypeMap[supplier.typeCode],
          typeCode: supplier.typeCode
        }
      })

      console.log('更新后的供应商列表:', suppliers.value)
    } else {
      console.warn('加载供应商信息失败:', res.data.message)
      ElMessage.error(res.data.message || '加载供应商信息失败')
    }
  } catch (error) {
    console.error('获取供应商信息失败:', error)
    ElMessage.error('获取供应商信息失败')
  }
}

// 打开供应商弹窗
const 
openSupplierDialog = (supplier: Supplier) => {
  console.log('打开供应商弹窗，当前供应商数据:', supplier)
  currentSupplier.value = supplier
  
  // 设置表单数据
  supplierForm.value = {
    id: supplier.id,
    batch: route.query.Batch as string,
    type: supplier.typeCode,
    supplierBatch: supplier.supplierBatch || '' // 确保设置现有的批次号
  }
  
  console.log('设置的表单数据:', supplierForm.value)
  supplierDialogVisible.value = true
}

// 保存供应商信息
const handleSupplierSave = async () => {
  if (!supplierFormRef.value) return

  await supplierFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        const currentSupplierData = currentSupplier.value
        if (!currentSupplierData) {
          ElMessage.error('当前供应商数据无效')
          return
        }

        // 构造保存数据
        const saveData = {
          id: currentSupplierData.id,
          batch: route.query.Batch as string,
          type: currentSupplierData.typeCode,
          supplierBatch: supplierForm.value.supplierBatch.trim() // 去除可能的空格
        }

        console.log('准备保存供应商数据:', {
          ...saveData,
          typeText: supplierTypeMap[saveData.type] // 添加类型文本用于日志
        })
        
        const res = await axios.post("http://localhost:5045/api/Supplier/AddSupplier", saveData)
        
        if (res.data.code === 200) {
          ElMessage.success(`${supplierTypeMap[saveData.type]}供应商信息保存成功`)
          supplierDialogVisible.value = false
          
          // 重新加载数据以更新显示
          await loadSupplierInfo()
        } else {
          ElMessage.error(res.data.message || '保存失败')
        }
      } catch (error) {
        console.error('保存供应商信息失败:', error)
        ElMessage.error('保存失败')
      }
    }
  })
}

// 组件挂载时初始化数据
onMounted(async () => {
  console.log('组件挂载，开始初始化数据')
  const batch = route.query.Batch
  if (batch) {
    try {
      console.log('初始化供应商列表:', initializeSuppliers())
      suppliers.value = initializeSuppliers() // 确保先初始化所有类型的供应商
      console.log('开始加载所有数据，batch:', batch)
      await Promise.all([
        loadSupplierInfo(),
        LoadInfo(),
        loadCultivationList(),
        loadHealthcareList(),
        loadCompanyInfo(),
        loadSlaughterInfo(),
        loadSlaughterCompanyInfo(),
        loadDeepInfo(),
 
      ]);
      console.log('所有数据加载完成')
    } catch (error) {
      console.error('初始化数据失败:', error)
    }
  }
})

// 监听标签页变化
watch(activeTab, async (newTab) => {
  if (newTab === 'deep') {
    const batch = route.query.Batch
    if (batch) {
      try {
        await Promise.all([
          loadDeepInfo(),
      
        ]);
      } catch (error) {
        console.error('加载深加工相关信息失败:', error)
      }
    }
  }
})

// 监听批次变化
watch(
  () => route.query.Batch,
  async (newBatch) => {
    console.log('批次变化，重新加载数据:', newBatch)
    if (newBatch) {
      if (activeTab.value === 'deep') {
        await Promise.all([
          loadDeepInfo(),

        ]);
      }
      await loadSupplierInfo()
    }
  }
)



// 在 script setup 部分添加日期格式化函数
const formatDateTime = (dateStr: string) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}年${month}月${day}日 ${hours}:${minutes}:${seconds}`
}

// 格式化日期，只显示年月日
const formatDate = (dateString: string): string => {
  if (!dateString) return ''
  const date = new Date(dateString)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 添加省市代码转换函数
const getProvinceNameByCode = (code: string): string => {
  const province = provinceAndCityData.find((p: any) => p.value === code)
  return province ? province.label : code
}

const getCityNameByCode = (provinceCode: string, cityCode: string): string => {
  const province = provinceAndCityData.find((p: any) => p.value === provinceCode)
  if (province && province.children) {
    const city = province.children.find((c: any) => c.value === cityCode)
    return city ? city.label : cityCode
  }
  return cityCode
}

// 定义屠宰信息接口
interface SlaughterInfo {
  id: number;
  batch: string;
  counterBalance: string;  // 保持为string类型，因为是从input输入的
  arrivalTime: string | null;  // 可能为null的日期字符串
  slaughter_Time: string | null;  // 可能为null的日期字符串
}

// 屠宰信息表单
const slaughterForm = ref<SlaughterInfo>({
  id: 0,
  batch: '',
  counterBalance: '',
  arrivalTime: '',
  slaughter_Time: ''
})

// 屠宰信息显示
const slaughterInfo = ref<SlaughterInfo>({
  id: 0,
  batch: '',
  counterBalance: '',
  arrivalTime: '',
  slaughter_Time: ''
})

// 加载屠宰信息
const loadSlaughterInfo = async () => {
  const batch = route.query.Batch;
  try {
    const res = await axios.get("http://localhost:5045/api/Slaughte/GetSlaughteShow", {
      params: { batch }
    });
    
    if (res.data.code === 200 && res.data.data) {
      const data = Array.isArray(res.data.data) ? res.data.data[0] : res.data.data;
      if (data) {
        slaughterInfo.value = {
          id: data.id || 0,
          batch: data.batch || '',
          counterBalance: data.counterBalance || '',
          arrivalTime: data.arrivalTime || '',
          slaughter_Time: data.slaughter_Time || ''
        };
      } else {
        // 如果没有数据，使用空值但不提示错误
        slaughterInfo.value = {
          id: 0,
          batch: '',
          counterBalance: '',
          arrivalTime: '',
          slaughter_Time: ''
        };
      }
    }
  } catch (error) {
    console.error('获取屠宰信息失败:', error);
    // 出错时使用空值但不提示错误
    slaughterInfo.value = {
      id: 0,
      batch: '',
      counterBalance: '',
      arrivalTime: '',
      slaughter_Time: ''
    };
  }
}

// 添加保健信息
const saveHealthcareRow = async () => {
  const editingRow = healthcareList.value.find(row => row.editing)
  if (!editingRow) return

  try {
    const data = {
      id: editingRow.id,
      days: editingRow.days,
      way: editingRow.way,
      method: editingRow.method,
      batch: typeof route.query.Batch === 'string' ? route.query.Batch : ''
    }

    // 根据是否有ID决定是添加还是更新
    const url = editingRow.id === 0 ? 
      "http://localhost:5045/api/Health/AddHealth" : 
      "http://localhost:5045/api/Health/UpdateHealth"
    
    const res = await axios[editingRow.id === 0 ? 'post' : 'put'](url, data)
    
    if (res.data.code === 200) {
      ElMessage.success(res.data.message)
      await loadHealthcareList() // 重新加载列表以获取最新数据
    } else {
      ElMessage.error(res.data.message)
    }
  } catch (e) {
    console.error('保存失败:', e)
    ElMessage.error('保存失败')
  }
}

// 修改保健信息
const editHealthcareRow = async (row: any) => {
  try {
    const res = await axios.put("http://localhost:5045/api/Health/UpdateHealth", {
      id: row.id,
      days: row.days,
      way: row.way,
      method: row.method,
      batch: row.batch
    })
    if (res.data.code === 200) {
      ElMessage.success(res.data.message)
      await loadHealthcareList() // 重新加载列表
    } else {
      ElMessage.error(res.data.message)
    }
  } catch (e) {
    console.error('修改失败:', e)
    ElMessage.error('修改失败')
  }
}

// 删除保健信息
const deleteHealthcareRow = async (id: any) => {
  try {
    const res = await axios.delete("http://localhost:5045/api/Health/DeleteHealth", {
      params: { id }
    })
    if (res.data.code === 200) {
      ElMessage.success(res.data.message)
      await loadHealthcareList() // 重新加载列表
    } else {
      ElMessage.error(res.data.message)
    }
  } catch (e) {
    console.error('删除失败:', e)
    ElMessage.error('删除失败')
  }
}
const healthcareList = ref<Array<{
  id: number;
  days: number|null;
  way: string;
  method: string;
  editing: boolean;
  batch: string;
}>>([])

// 加载保健信息列表
const loadHealthcareList = async () => {
  const batch = route.query.Batch
  try {
    const res = await axios.get("http://localhost:5045/api/Health/GetHealthShow", { 
      params: { batch } 
    })
    if (res.data.code === 200 && res.data.data) {
      healthcareList.value = res.data.data.map((item: any) => ({
        id: item.id,
        days: item.days,
        way: item.way,
        method: item.method,
        batch: item.batch,
        editing: false
      }))
      console.log('保健信息列表：', healthcareList.value)
    } else {
      ElMessage.error(res.data.message || '获取保健信息失败')
    }
  } catch (e) {
    console.error('获取保健信息失败:', e)
    ElMessage.error('获取保健信息失败')
  }
}
function addHealthcareRow() {
  healthcareList.value.push({ 
    id: 0,
    days: null, 
    way: '', 
    method: '', 
    editing: true,
    batch: typeof route.query.Batch === 'string' ? route.query.Batch : ''
  })
}

// 取消按钮
function cancelHealthcareRow(index: number) {
  const row = healthcareList.value[index]
  if (!row.days && !row.method && !row.way) {
    healthcareList.value.splice(index, 1)
  } else {
    loadHealthcareList() // 重新加载列表，恢复原始数据
  }
}

// 开始编辑行
function startEditing(row: any) {
  // 先将所有行的编辑状态设为false
  healthcareList.value.forEach(item => {
    item.editing = false
  })
  // 将当前行设为编辑状态
  row.editing = true
}

// 打开养殖信息弹窗
function openFarmingDialog() {
  const batch = typeof route.query.Batch === 'string' ? route.query.Batch : '';
  // 如果已有数据，则使用现有数据进行编辑
  if (farmingInfo.value.breed) {
    farmingForm.value = { ...farmingInfo.value };
  } else {
    // 否则初始化空表单用于添加
    farmingForm.value = {
      id: 0,
      breed: '',
      source: '',
      days: '',
      brand: '',
      caretaker: '',
      departure: '',
      batch: batch
    }
  }
  farmingDialogVisible.value = true
}

// 保存养殖信息（添加或修改）
const handleFarmingSave = async () => {
  if (!farmingFormRef.value) return
  
  await farmingFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        const data = {
          ...farmingForm.value,
          batch: typeof route.query.Batch === 'string' ? route.query.Batch : '',
          departure: farmingForm.value.departure ? farmingForm.value.departure.split('T')[0] : ''
        }

        const res = await axios.post("http://localhost:5045/api/Traceability/UpdateCultivation", data)
        if (res.data.code === 200) {
          ElMessage.success(res.data.message)
          farmingDialogVisible.value = false
          // 重新加载养殖信息
          await loadCultivationList()
        } else {
          ElMessage.error(res.data.message)
        }
      } catch (error) {
        console.error('保存养殖信息失败:', error)
        ElMessage.error('保存养殖信息失败')
      }
    }
  })
}

function openCompanyDialog() {
  companyDialogVisible.value = true
}

// 保存养殖企业信息（添加或修改使用同一个接口）
async function handleCompanySave() {
  if (!companyFormRef.value) return

  await companyFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const data = {
          id: companyForm.id,
          farm: companyForm.farm,
          principal: companyForm.principal,
          number: companyForm.number,
          batch: typeof route.query.Batch === 'string' ? route.query.Batch : ''
        }

        // 使用统一的接口，后端会根据batch判断是添加还是修改
        const res = await axios.post("http://localhost:5045/api/Company/AddCultivation", data)
        
        if (res.data.code === 200) {
          ElMessage.success(res.data.message)
          companyDialogVisible.value = false
          // 重新加载企业信息
          await loadCompanyInfo()
        } else {
          ElMessage.error(res.data.message)
        }
      } catch (error) {
        console.error('保存企业信息失败:', error)
        ElMessage.error('保存企业信息失败')
      }
    }
  })
}

function removeSlaughterCert(idx: number) {
  slaughterCerts.value.splice(idx, 1)
}
function handleSlaughterCertUpload(file: any) {}











// 屠宰信息弹窗相关
const slaughterDialogVisible = ref(false)
const slaughterFormRef = ref<FormInstance>()
// 屠宰信息表单验证规则
const slaughterRules = reactive<FormRules>({
  batch: [
    { required: true, message: '请输入批次', trigger: 'blur' },

  ],
  counterBalance: [
    { required: true, message: '请输入到厂均重', trigger: 'blur' },
    { pattern: /^\d{1,5}$/, message: '仅限数字，最多5位', trigger: 'blur' }
  ],
  arrivalTime: [
    { required: true, message: '请选择到厂时间', trigger: 'change' }
  ],
  slaughter_Time: [
    { required: true, message: '请选择屠宰时间', trigger: 'change' }
  ]
})

// 修改显示信息的接口
interface SlaughterCompanyInfo {
  id: number;
  companyName: string;
  companyAddress: string;
  establishedTime: string;
  resume: string;
  cityName: string;
  regionName: string;
  provinceName: string;
}

// 修改表单数据的接口
interface SlaughterCompanyForm {
  id: number;
  companyName: string;
  companyAddress: string[];  // 用于级联选择器，现在只需要省市两级
  regionName: string;  // 替换原来的 addressDetail
  establishedTime: string;
  resume: string;
  batch: string;
  cityName: string;
  provinceName: string;
}

// 修改保存数据的接口
interface SlaughterCompanySaveData {
  id: number;
  companyName: string;
  provinceName: string;
  cityName: string;
  regionName: string;
  addressDetail: string;  // 保持与后端一致
  establishedTime: string;
  resume: string;
  batch: string;
  fullAddress: string;
}

// 屠宰企业信息弹窗相关
const slaughterCompanyDialogVisible = ref(false)
const slaughterCompanyFormRef = ref<FormInstance>()

// 修改验证规则
const slaughterCompanyRules = reactive<FormRules>({
  companyName: [
    { required: true, message: '请输入公司名称', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5a-zA-Z]{1,30}$/, message: '仅限中文或字母，最多30位', trigger: 'blur' }
  ],
  companyAddress: [
    { required: true, message: '请选择省市', trigger: 'change' }
  ],
  regionName: [
    { required: true, message: '请输入详细地址', trigger: 'blur' },
    { max: 100, message: '最多100位字符', trigger: 'blur' }
  ],
  establishedTime: [
    { required: true, message: '请选择成立时间', trigger: 'change' }
  ],
  resume: [
    { required: false },
    { max: 500, message: '最多500位字符', trigger: 'blur' }
  ]
})

// 使用省市数据，过滤掉区级数据
const addressOptions = provinceAndCityData.map((province: any) => ({
  label: province.label,
  value: province.value,
  children: province.children ? province.children.map((city: any) => ({
    label: city.label,
    value: city.value
  })) : []
}))

// 地址选择变化处理函数
const handleAddressChange = (value: string[]) => {
  if (value.length >= 2) {
    slaughterCompanyForm.value.provinceName = value[0]
    slaughterCompanyForm.value.cityName = value[1]
    slaughterCompanyForm.value.regionName = '' // 清空区级数据
  }
}

const slaughterCompanyInfo = ref<SlaughterCompanyInfo>({
  id: 0,
  companyName: '',
  companyAddress: '',
  establishedTime: '',
  resume: '',
  cityName: '',
  regionName: '',
  provinceName: ''
})

const slaughterCompanyForm = ref<SlaughterCompanyForm>({
  id: 0,
  companyName: '',
  companyAddress: [],
  regionName: '',
  establishedTime: '',
  resume: '',
  batch: typeof route.query.Batch === 'string' ? route.query.Batch : '',
  cityName: '',
  provinceName: ''
})

// 加载屠宰企业信息
const loadSlaughterCompanyInfo = async () => {
  const batch = route.query.Batch
  if (!batch) {
    console.warn('生产批次不存在')
    return
  }

  try {
    const res = await axios.get("http://localhost:5045/api/Slaughte/GetSlaughterTableShow", {
      params: { batch }
    })
    if (res.data.code === 200 && res.data.data && res.data.data.length > 0) {
      const data = res.data.data[0]
      
      // 转换省市代码为名称
      const provinceName = getProvinceNameByCode(data.provinceName)
      const cityName = getCityNameByCode(data.provinceName, data.cityName)

      // 更新显示数据
      slaughterCompanyInfo.value = {
        id: data.id || 0,
        companyName: data.companyName || '',
        companyAddress: [provinceName, cityName, data.regionName].filter(Boolean).join(' ') || '',
        establishedTime: formatDate(data.establishedTime) || '',
        resume: data.resume || '',
        cityName: cityName,
        regionName: data.regionName || '',
        provinceName: provinceName
      }

      console.log('加载的屠宰企业信息：', slaughterCompanyInfo.value) // 添加日志
    } else {
      console.warn('未找到屠宰企业信息') // 添加日志
      // 如果没有数据，清空显示
      slaughterCompanyInfo.value = {
        id: 0,
        companyName: '',
        companyAddress: '',
        establishedTime: '',
        resume: '',
        cityName: '',
        regionName: '',
        provinceName: ''
      }
    }
  } catch (error) {
    console.error('获取企业信息失败:', error)
    ElMessage.error('获取企业信息失败')
  }
}

// 监听路由参数变化，自动加载企业信息
watch(
  () => route.query.Batch,
  (newBatch) => {
    if (newBatch) {
      loadSlaughterCompanyInfo()
    }
  },
  { immediate: true }
)

// 转换表单数据为保存格式
const transformFormToSaveData = (form: SlaughterCompanyForm): SlaughterCompanySaveData => {
  // 获取选中的省市代码
  const provinceName = form.companyAddress[0] || form.provinceName || ''
  const cityName = form.companyAddress[1] || form.cityName || ''
  
  return {
    id: form.id, // 保留id，用于后端判断是新增还是修改
    companyName: form.companyName,
    provinceName: provinceName,
    cityName: cityName,
    regionName: form.regionName,
    addressDetail: form.regionName, // 保持与后端字段一致
    establishedTime: form.establishedTime,
    resume: form.resume,
    batch: form.batch,
    fullAddress: [
      getProvinceNameByCode(provinceName),
      getCityNameByCode(provinceName, cityName),
      form.regionName
    ].filter(Boolean).join(' ')
  }
}

// 打开弹窗时加载数据
const openSlaughterCompanyDialog = async () => {
  const batch = route.query.Batch
  if (!batch) {
    ElMessage.error('生产批次不能为空')
    return
  }

  // 先打开弹窗
  slaughterCompanyDialogVisible.value = true

  try {
    const res = await axios.get("http://localhost:5045/api/Slaughte/GetSlaughterTableShow", {
      params: { batch }
    })
    
    if (res.data.code === 200) {
      if (res.data.data && res.data.data.length > 0) {
        // 有数据时，填充表单进行修改
        const data = res.data.data[0]
        
        // 转换省市代码为名称
        const provinceName = getProvinceNameByCode(data.provinceName)
        const cityName = getCityNameByCode(data.provinceName, data.cityName)
        
        slaughterCompanyForm.value = {
          id: data.id,
          companyName: data.companyName || '',
          companyAddress: [data.provinceName, data.cityName], // 使用原始代码，而不是转换后的名称
          regionName: data.regionName || '',
          establishedTime: data.establishedTime ? data.establishedTime.split('T')[0] : '', // 只取日期部分
          resume: data.resume || '',
          batch: batch as string,
          cityName: data.cityName || '',
          provinceName: data.provinceName || ''
        }
      } else {
        // 无数据时，重置表单进行添加
        slaughterCompanyForm.value = {
          id: 0,
          companyName: '',
          companyAddress: [],
          regionName: '',
          establishedTime: '',
          resume: '',
          batch: batch as string,
          cityName: '',
          provinceName: ''
        }
      }
    }
  } catch (error) {
    console.error('获取企业信息失败:', error)
    // 即使获取数据失败，也保持弹窗打开状态，允许用户添加新数据
    slaughterCompanyForm.value = {
      id: 0,
      companyName: '',
      companyAddress: [],
      regionName: '',
      establishedTime: '',
      resume: '',
      batch: batch as string,
      cityName: '',
      provinceName: ''
    }
  }
}

// 保存屠宰的企业信息
const handleSlaughterCompanySave = async () => {
  if (!slaughterCompanyFormRef.value) return
  
  await slaughterCompanyFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        const form = slaughterCompanyForm.value
        // 确保所有必要的地址信息都存在
        if (!form.companyAddress || form.companyAddress.length < 2) {
          ElMessage.error('请选择完整的省市信息')
          return
        }

        // 转换并保存数据
        const saveData = transformFormToSaveData(form)
        const res = await axios.post("http://localhost:5045/api/Slaughte/AddSlaughterTable", saveData)
        
        if (res.data.code === 200) {
          ElMessage.success(res.data.message || (form.id ? '修改成功' : '添加成功'))
          slaughterCompanyDialogVisible.value = false
          // 重新加载企业信息以更新显示
          await loadSlaughterCompanyInfo()
        } else {
          ElMessage.error(res.data.message || '保存失败')
        }
      } catch (error) {
        console.error('保存失败:', error)
        ElMessage.error('保存失败')
      }
    }
  })
}

// 深加工企业信息相关


const deepCompanyDialogVisible = ref(false)
const deepCompanyFormRef = ref<FormInstance>()

// 深加工企业信息表单验证规则
const deepCompanyRules = reactive<FormRules>({
  companyName: [
    { required: true, message: '请输入公司名称', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5a-zA-Z]{1,30}$/, message: '仅限中文或字母，最多30位', trigger: 'blur' }
  ],
  license_Number: [
    { required: true, message: '请输入生产许可证号', trigger: 'blur' },
    { pattern: /^[A-Za-z0-9]{1,30}$/, message: '仅限数字和字母，最多30位', trigger: 'blur' }
  ]
})

// 打开深加工企业信息弹窗
const openDeepCompanyDialog = async () => {
  const batch = route.query.Batch;
  if (!batch) {
    ElMessage.error('生产批次不能为空');
    return;
  }

  deepCompanyDialogVisible.value = true;
};





// ... existing code ...

console.log('当前标签页:', activeTab.value)
console.log('深加工信息:', deepInfoForm.value)


function removeSupplierMaterial(sidx: number, idx: number) {
  suppliers.value[sidx].materials.splice(idx, 1)
}
function handleSupplierMaterialUpload(sidx: number, file: any) {}

function goBack() { /* 返回逻辑 */ }

// 供应商状态管理
const supplierDialogVisible = ref(false)
const supplierFormRef = ref<FormInstance>()
const currentSupplier = ref<Supplier | null>(null)

// 供应商表单数据
const supplierForm = ref({
  id: 0,
  batch: '',
  type: 1,
  supplierBatch: ''
})

// 供应商表单验证规则
const supplierRules = reactive<FormRules>({
  supplierBatch: [
    { required: true, message: '请输入供应商生产批次', trigger: 'blur' },
    { pattern: /^[A-Za-z0-9]{1,20}$/, message: '仅限数字和字母，最多20位', trigger: 'blur' },
    { whitespace: true, message: '批次号不能为空格', trigger: 'blur' }
  ]
})


// ... existing code ...

// 恢复必要的方法
const openSlaughterDialog = () => {
  const batch = typeof route.query.Batch === 'string' ? route.query.Batch : ''
  // 如果已有数据，则使用现有数据进行编辑
  if (slaughterInfo.value.batch) {
    slaughterForm.value = { ...slaughterInfo.value }
  } else {
    // 否则初始化空表单用于添加，但使用路由中的批次号
    slaughterForm.value = {
      id: 0,
      batch: batch,
      counterBalance: '',
      arrivalTime: '',
      slaughter_Time: ''
    }
  }
  slaughterDialogVisible.value = true
}

// 保存屠宰信息
const handleSlaughterSave = async () => {
  if (!slaughterFormRef.value) return

  await slaughterFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 处理时区问题，保持本地时间
        const formatToLocalISOString = (dateStr: string) => {
          if (!dateStr) return ''
          const date = new Date(dateStr)
          const year = date.getFullYear()
          const month = String(date.getMonth() + 1).padStart(2, '0')
          const day = String(date.getDate()).padStart(2, '0')
          const hours = String(date.getHours()).padStart(2, '0')
          const minutes = String(date.getMinutes()).padStart(2, '0')
          const seconds = String(date.getSeconds()).padStart(2, '0')
          return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}`
        }

        const data = {
          ...slaughterForm.value,
          batch: typeof route.query.Batch === 'string' ? route.query.Batch : '',
          arrivalTime: formatToLocalISOString(slaughterForm.value.arrivalTime || ''),
          slaughter_Time: formatToLocalISOString(slaughterForm.value.slaughter_Time || '')
        }

        const res = await axios.post("http://localhost:5045/api/Slaughte/AddSlaughte", data)
        
        if (res.data.code === 200) {
          ElMessage.success(res.data.message)
          slaughterDialogVisible.value = false
          await loadSlaughterInfo()
        } else {
          ElMessage.error(res.data.message)
        }
      } catch (error) {
        console.error('保存屠宰信息失败:', error)
        ElMessage.error('保存屠宰信息失败')
      }
    }
  })
}
</script>

<style scoped>
.traceability-detail { padding: 24px; }
.header { margin-bottom: 16px; }
.mb16 { margin-bottom: 16px; }
.product-img {
  width: 140px;
  height: 140px;
  border-radius: 8px;
  object-fit: cover;
}
.product-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 16px;
}
.product-info-row {
  margin-bottom: 8px;
}
.section-title {
  font-weight: bold;
  font-size: 16px;
}
.tab-header { display: flex; justify-content: flex-end; margin-bottom: 8px; }
.standard-uploader {
  margin: 16px 0;
}
</style>



